<?php
/**
 * +--------------------------------------------------------+
 * @Created by Phpstorm.
 * @Category Helpers.php
 * @Depiction
 * @Author hwy
 * @Date 2021/3/15  13:47
 * +--------------------------------------------------------+
 */

use Carbon\Carbon;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\Cache;
use App\Models\SettingConfig;
use App\Exceptions\ResponseException;
use Illuminate\Support\Facades\DB;

if (!function_exists('curl')) {
    /**
     * @param $url
     * @param false $params
     * @param int $ispost
     * @param int $https
     * @param int $type 1:正常 2：返回请求 3：302跳转返回真实请求URL
     * @param string $headers
     * @return bool|CurlHandle|resource|string
     * @Depiction
     * @Author hwy
     * @Date 2021/3/15  14:46
     */
    function curl($url, $params = false, $ispost = 0, $https = 0, $type = 1, $headers = '')
    {

        $httpInfo = [];
        $ch       = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 25);
        curl_setopt($ch, CURLOPT_TIMEOUT, 25);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($type == 3) {
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 302 redirect
        }
        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        if ($https or 1) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        }
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                if (is_array($params)) {
                    $params = http_build_query($params);
                }
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        if ($type == 2) {
            return $ch;
        }
        $response = curl_exec($ch);
        //增加curl日志

        $log_curl['url']        = $url;
        $log_curl['input']      = is_string($params) ? $params : json_encode($params);
        $log_curl['created_at'] = Carbon::now()->toDateTimeString();
        if ($response === false) {
            // echo "cURL Error: " . curl_error($ch);
            $log_curl['result'] = curl_error($ch);
            $log_curl['status'] = 2;
        } else {
            $responses = iconv("gb2312", "utf-8//IGNORE", $response);
            $result    = is_string($responses) ? $responses : json_encode($responses);
            if (strlen($result) > 2000) {
                $result = 'too long';
            }
            $log_curl['result'] = $result;
            $log_curl['status'] = 1;
        }
        if ($type == 3) {
            $redirect_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
        }
        // $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        dispatch((new \App\Jobs\LogCurlJob($log_curl))->onQueue('default'));
        curl_close($ch);

        if ($type == 3) {
            if ($redirect_url == $url) {
                return 'same';
            }
            return $redirect_url;
        }
        return $response;
    }


    if (!function_exists('setting')) {
        /**
         * @param string $k
         * @param bool $isCache
         * @return bool|\Illuminate\Config\Repository|mixed|null
         * @Depiction 使用config()缓存失败，问题未知。先用cache代替
         * @Author hwy
         * @Date  2020/10/13  17:57
         */
        function sys_config($k = 'all', $isCache = true)
        {
            $cache = null;
            if ($isCache) {
                $cache = Cache::get($k);
            }
            //如果缓存不为空直接返回
            if (null != $cache) {
                return $cache;
            }

            //判断是否查询全部设置项
            if ($k == 'all') {
                $setting = SettingConfig::get()->pluck('value', 'menu_name');
                foreach ($setting as $key => $v) {
                    $config[$key] = $v;
                }
                $data = $config;

            } else {
                $result = SettingConfig::where("menu_name", $k)->first();
                $data   = $result['value'];

            }
            //建立缓存
            if ($data) {
                //                config([$k=>$data]);
                Cache::put($k, $data, 60*60*24);
            }
            return $data;
        }
    }

    if (!function_exists('array_get')) {
        /**
         * @param $array
         * @param $key
         * @param null $default
         * @return mixed
         * @Depiction 获取数组指定主键
         * @Author hwy
         * @Date 2021/4/20  15:15
         */
        function array_get($array, $key, $default = null)
        {
            return Arr::get($array, $key, $default);
        }
    }

    if (!function_exists('sort_data_list')) {
        /**
         * 树 排列
         * @param $data
         * @param int $pid
         * @param string $field
         * @param string $pk
         * @param string $html
         * @param int $level
         * @param bool $clear
         * @return array
         * @Depiction
         * @Author hwy
         * @Date  2020/6/17  16:22
         */
        function sort_data_list($data, $pid = 0, $field = 'pid', $pk = 'id', $html = '|----', $level = 1, $clear = true)
        {
            static $list = [];
            if ($clear)
                $list = [];
            foreach ($data as $k => $res) {
                if ($res[$field] == $pid) {
                    $res['html'] = str_repeat($html, $level);
                    $list[]      = $res;
                    unset($data[$k]);
                    sort_data_list($data, $res[$pk], $field, $pk, $html, $level + 1, false);
                }
            }
            return $list;
        }
    }


    if (!function_exists('substr_format')) {

        /**
         * @param $text
         * @param $length
         * @param string $replace
         * @param string $encoding
         * @return string
         * @Depiction 字符串加点操作
         * @Author hwy
         * @Date 2021/4/20  15:15
         */
        function substr_format($text, $length, $replace = '...', $encoding = 'UTF-8')
        {
            if ($text && mb_strlen($text, $encoding) > $length) {
                return mb_substr($text, 0, $length, $encoding) . $replace;
            }
            return $text;
        }
    }

    if (!function_exists('get_data_time')) {

        /**
         * @param $time
         * @param int $type
         * @return int|string
         * @Depiction 获取时间信息
         * @Author hwy
         * @Date 2021/4/20  15:14
         */
        function get_data_time($time, $type = 1)
        {
            empty($time) ? $time = Carbon::now() : $time = Carbon::parse($time);

            if ($type == 1) {
                $data = $time->year;
            } elseif ($type == 2) {
                $data = $time->month;
            } elseif ($type == 3) {
                $data = $time->day;
            } elseif ($type == 4) {
                $data = $time->hour;
            } elseif ($type == 5) {
                $data = $time->minute;
            } elseif ($type == 6) {
                $data = $time->second;
            } else {
                $data = '';
            }

            return $data;
        }
    }
    if (!function_exists('return_success_msg')) {
        /**
         * @param string $message
         * @param array $data
         * @param int $code
         * @return array
         * @Depiction 成功信息返回
         * @Author hwy
         * @Date 2021/3/15  14:49
         */
        function return_success_msg($message = ResponseException::REQUEST_SUCCESS_MESSAGE, $data = [], $code = ResponseException::SUCCESS_CODE): array
        {
            $retuen['code']    = (int)$code;
            $retuen['message'] = $message;
            $retuen['data']    = $data;

            return $retuen;
        }
    }

    if (!function_exists('return_error_msg')) {
        /**
         * @param string $message
         * @param array $data
         * @param int $code
         * @return array
         * @Depiction 错误信息返回
         * @Author hwy
         * @Date 2021/3/15  14:49
         */
        function return_error_msg($message = ResponseException::REQUEST_ERROR_MESSAGE, $data = [], $code = ResponseException::ERROR_CODE): array
        {
            $retuen['code']    = (int)$code;
            $retuen['message'] = $message;
            $retuen['data']    = $data;

            return $retuen;
        }
    }

    if (!function_exists('exception_msg')) {
        /**
         * @param string $message
         * @param array $data
         * @param int $code
         * @return array
         * @Depiction 异常信息返回
         * @Author hwy
         * @Date 2021/3/15  14:49
         */
        function exception_msg($message = ResponseException::UNKNOW_ERROR_MESSAGE): array
        {
            if (config('app.debug')) {
                return $message;
            }

            return ResponseException::UNKNOW_ERROR_MESSAGE;


        }
    }


    if (!function_exists('get_file_info')) {
        /**
         * @param $file_id
         * @return mixed
         * @Depiction 获取文件信息
         * @Author hwy
         * @Date 2021/4/20  15:12
         */
        function get_file_info($file_id)
        {
            $file = \App\Models\File::find($file_id);

            return $file;
        }
    }

    if (!function_exists('get_sqls')) {
        /**
         * @Depiction 数据库临时排查方法
         * @Author hwy
         * @Date 2021/4/20  15:11
         */
        function get_sqls()
        {
            DB::listen(
                function (QueryExecuted $event) {

                    $res = init_sql_statement($event);
                    [$sql, $time] = $res;

                    echo $sql;
                    echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                    if ($time < 100) {
                        echo '<span style="color: #00f">time：' . $time . 'ms</span>';
                    } else {
                        //  增加日志记录;定位慢查询；可同步至sql监听
                        echo '<span style="color: #f00">time：' . $time . 'ms</span>';
                    }

                    echo '<br>';
                }
            );
        }
    }

    if (!function_exists('init_sql_statement')) {
        /**
         * @param $event
         * @return array
         * @Depiction 数据库语句格式化
         * @Author hwy
         * @Date 2021/3/15  15:02
         */
        function init_sql_statement($event): array
        {
            $sql      = $event->sql;
            $bindings = $event->bindings;
            $time     = $event->time;

            $bindings = array_map(function ($binding) {
                if (is_string($binding)) {
                    return "'$binding'";
                } else if ($binding instanceof \DateTime) {
                    return $binding->format("'Y-m-d H:i:s'");
                }
                return $binding;
            }, $bindings);

            $sql = str_replace('?', '%s', $sql);
            $sql = sprintf($sql, ...$bindings);
            //$sql = vsprintf($sql, $bindings);

            return [$sql, $time];
        }
    }

    if (!function_exists('uniqu_arr')) {
        /**
         * @param $array
         * @param string $ele
         * @return array
         * @Depiction 数组去重
         * @Author hwy
         * @Date 2021/4/20  15:12
         */
        function uniqu_arr($array, $ele = 'title'): array
        {
            $result = [];
            foreach ($array as $k => $val) {
                $code = false;
                foreach ($result as $_val) {
                    if ($_val[$ele] == $val[$ele]) {
                        $code = true;
                        break;
                    }
                }
                if (!$code) {
                    $result[] = $val;
                }
            }
            return $result;
        }
    }


}
